/*
 *                 [[ Frozen-Bubble ]]
 *
 * Copyright (c) 2000-2003 Guillaume Cottenceau.
 * Java sourcecode - Copyright (c) 2003 Glenn Sanson.
 *
 * This code is distributed under the GNU General Public License
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * version 2, as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 *
 * Artwork:
 *    Alexis Younes <73lab at free.fr>
 *      (everything but the bubbles)
 *    Amaury Amblard-Ladurantie <amaury at linuxfr.org>
 *      (the bubbles)
 *
 * Soundtrack:
 *    Matthias Le Bidan <matthias.le_bidan at caramail.com>
 *      (the three musics and all the sound effects)
 *
 * Design & Programming:
 *    Guillaume Cottenceau <guillaume.cottenceau at free.fr>
 *      (design and manage the project, whole Perl sourcecode)
 *
 * Java version:
 *    Glenn Sanson <glenn.sanson at free.fr>
 *      (whole Java sourcecode, including JIGA classes
 *             http://glenn.sanson.free.fr/jiga/)
 *
 * Android port:
 *    Pawel Aleksander Fedorynski <pfedor@fuw.edu.pl>
 *    Copyright (c) Google Inc.
 *
 *          [[ http://glenn.sanson.free.fr/fb/ ]]
 *          [[ http://www.frozen-bubble.org/   ]]
 */
// This file is derived from the LunarLander.java file which is part of
// the Lunar Lander game included with Android documentation.  The copyright
// notice for the Lunar Lander is reproduced below.
/*
 * Copyright (C) 2007 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package game_FrozenBubble;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Looper;
import android.os.Message;
import android.os.Vibrator;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Vector;

import android.os.Handler;
import android.provider.Settings.Global;
import android.bluetooth.*;
import android.util.Log;

import com.BioSensor.SensorConnectionManager;
import com.gmsi_prototype.R;
import com.shimmerresearch.driver.*;

import game_FrozenBubble.GameView;
import game_FrozenBubble.GameView.GameThread;

public class FrozenBubble extends Activity
{
	public final static int SOUND_WON = 0;
	public final static int SOUND_LOST = 1;
	public final static int SOUND_LAUNCH = 2;
	public final static int SOUND_DESTROY = 3;
	public final static int SOUND_REBOUND = 4;
	public final static int SOUND_STICK = 5;
	public final static int SOUND_HURRY = 6;
	public final static int SOUND_NEWROOT = 7;
	public final static int SOUND_NOH = 8;
	public final static int NUM_SOUNDS = 9;

	public final static int GAME_NORMAL = 0;
	public final static int GAME_COLORBLIND = 1;

	public final static int MENU_COLORBLIND_MODE_ON = 1;
	public final static int MENU_COLORBLIND_MODE_OFF = 2;
	public final static int MENU_FULLSCREEN_ON = 3;
	public final static int MENU_FULLSCREEN_OFF = 4;
	public final static int MENU_SOUND_ON = 5;
	public final static int MENU_SOUND_OFF = 6;
	public final static int MENU_DONT_RUSH_ME = 7;
	public final static int MENU_RUSH_ME = 8;
	public final static int MENU_NEW_GAME = 9;
	public final static int MENU_ABOUT = 10;
	public final static int MENU_EDITOR = 11;
	public final static int MENU_TOUCHSCREEN_AIM_THEN_SHOOT = 12;
	public final static int MENU_TOUCHSCREEN_POINT_TO_SHOOT = 13;

	public final static String PREFS_NAME = "frozenbubble";

	private static int gameMode = GAME_NORMAL;
	private static boolean soundOn = true;
	private static boolean dontRushMe = false;
	private static boolean aimThenShoot = false; // changing between dragging to shoot or tapping to shoot

	private boolean fullscreen = true;

	public GameThread mGameThread;
	private GameView mGameView;

	public double GSR = 0;
	public double currentGSR = 0;
	public Vector<Double> currentGSRvector = new Vector<Double>(10); 

	private static final String EDITORACTION = "org.jfedor.frozenbubble.GAME";
	private static final int REQUEST_ENABLE_BT = 3;
	private boolean activityCustomStarted = false;
	public BlueToothThread thread;

	//yson
	private static final long	timestamp = System.currentTimeMillis();

	final private static int HRV = 0;
	final private static int BR = 1;
	final private static int HR = 2;
	final private static int SCL = 3;
	final private static int SCR = 4;
	final private static int BH_SL = 5;
	final private static int SHIM_SL = 6;

	private Handler dataHandler = new Handler(Looper.getMainLooper()) {
		public void handleMessage(Message msg) {
			// Handle Data from Sensor Manager
			String data = null;
			switch (msg.what) {
			case BR:
				data = (String) msg.obj;
				Log.i("Data", "BR:" + data);
				break;

			case HR:
				data = (String) msg.obj;
				Log.i("Data", "HR:" + data);
				break;

			case HRV:
				data = (String) msg.obj;
				Log.i("Data", "HRV:" + data);
				break;

			case SCL:
				data = (String) msg.obj;
				Log.i("Data", "SCL:" + data);
				break;

			case SCR:
				data = (String) msg.obj;
				Log.i("Data", "SCR:" + data);
				break;

			case BH_SL:
				data = (String) msg.obj;
				Log.i("Data", "BH SL:" + data);
				mGameThread.setBioHarnssSL(data);
				break;
			
			case SHIM_SL:
				data = (String) msg.obj;
				Log.i("Data", "SHIM SL:" + data);
				mGameThread.setShimmerSL(data);
				break;

			default:
				break;
			};
		}
	};


	public class BlueToothThread extends Thread{
		//construct shimmer class object and connect to this Shimmer, only works with 
		//gSort shimmer , aka RN42- BC76
		//		String bluetoothAddress ="00:06:66:46:BD:70";

		SensorConnectionManager scm;
		boolean stillContinue;
		/*
		 * initialize Sensor Connection Manager 
		 */
		public BlueToothThread() {
			mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

			while (!mBluetoothAdapter.isEnabled()) {
				Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
				startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
			}

			scm = new SensorConnectionManager(mBluetoothAdapter);
//			sensor_names = scm.getAvailableSensors();
			stillContinue = true;
		}

		public void run(){
			Looper.prepare();
			sensor_names = null;
			Vector<String> vSenorNames = new Vector<String>();
			if(GlobalConstant.isCheck_BH_BR || GlobalConstant.isCheck_BH_HR || GlobalConstant.isCheck_BH_HRV) 
				vSenorNames.add("BioHarness");
			if(GlobalConstant.isCheck_Shim_SCL || GlobalConstant.isCheck_Shim_SCR) 
				vSenorNames.add("Shimmer");
			sensor_names = vSenorNames.toArray(new String[vSenorNames.size()]);
			
			
			try {
				scm.connectSensors(sensor_names);
//				ArrayList<String> conSens = scm.getConnectedSensors();
//				for(int i = 0; i < conSens.size(); ++i)
//				{
//					String[] devSens = scm.getDeviceSensors(conSens.get(i));
//					for(int j = 0; j < devSens.length; ++j)
//					{
//						scm.setThreshold(conSens.get(i), devSens[j], GlobalConstant.thresholds.get(i)[j]);
//						Log.d("Threshold",String.valueOf(GlobalConstant.thresholds.get(i)[j]));
//						
//					}
//				}
			} catch (IllegalArgumentException e) {
				Log.d("Exception",e.getMessage());
			}
			if(GlobalConstant.isCheck_BH_BR) 
				scm.setThreshold("BioHarness", "Respiration Rate", GlobalConstant.thresholdBHBR);
			if(GlobalConstant.isCheck_BH_HR) 
				scm.setThreshold("BioHarness", "Heart Rate", GlobalConstant.thresholdBHHR);
			if(GlobalConstant.isCheck_BH_HRV)
				scm.setThreshold("BioHarness", "HRV", GlobalConstant.thresholdBHHRV);
			if(GlobalConstant.isCheck_Shim_SCL)
				scm.setThreshold("Shimmer", "SCL", GlobalConstant.thresholdSHSCL);
			if(GlobalConstant.isCheck_Shim_SCR)
				scm.setThreshold("Shimmer", "SCR", GlobalConstant.thresholdSHSCR);
			
			
			
			
//			for(int i = 0; i < 1000; ++i)
			while(stillContinue){
				try {
					sleep(100);
					if(GlobalConstant.isCheck_BH_HR) {
						Message msg_HR = new Message();
						msg_HR.what = HR;
						msg_HR.obj = (Object) String.valueOf(scm.getRawData("BioHarness", "Heart Rate"));
						dataHandler.sendMessage(msg_HR);
					}

					if(GlobalConstant.isCheck_BH_BR) {
						Message msg_BR = new Message();
						msg_BR.what = BR;
						msg_BR.obj = (Object) String.valueOf(scm.getRawData("BioHarness", "Respiration Rate"));
						dataHandler.sendMessage(msg_BR);
					}

					if(GlobalConstant.isCheck_BH_HRV) {
						Message msg_HRV = new Message();
						msg_HRV.what = HRV;
						msg_HRV.obj = (Object) String.valueOf(scm.getRawData("BioHarness", "HRV"));
						dataHandler.sendMessage(msg_HRV);
					}

					if(GlobalConstant.isCheck_Shim_SCR) {
						Message msg_SCR = new Message();
						msg_SCR.what = SCR;
						msg_SCR.obj = (Object) String.valueOf(scm.getRawData("Shimmer", "SCR"));
						dataHandler.sendMessage(msg_SCR);
					}

					if(GlobalConstant.isCheck_Shim_SCL) {
						Message msg_SCL = new Message();
						msg_SCL.what = SCL;
						msg_SCL.obj = (Object) String.valueOf(scm.getRawData("Shimmer", "SCL"));
						dataHandler.sendMessage(msg_SCL);
					}
					if(GlobalConstant.isCheck_Shim_SCL || GlobalConstant.isCheck_Shim_SCR) {
						Message msg_SHIM_SL = new Message();
						
						Vector<String> data_SHIM = new Vector<String>();
						if(GlobalConstant.isCheck_Shim_SCL)
							data_SHIM.add("SCL");
						if(GlobalConstant.isCheck_Shim_SCR)
							data_SHIM.add("SCR");

						String[] data = data_SHIM.toArray(new String[data_SHIM.size()]);
						msg_SHIM_SL.what = SHIM_SL;
						msg_SHIM_SL.obj = (Object) String.valueOf(scm.getStressLevel("Shimmer", data));
						dataHandler.sendMessage(msg_SHIM_SL);
					}

					if(GlobalConstant.isCheck_BH_BR || GlobalConstant.isCheck_BH_HR || GlobalConstant.isCheck_BH_HRV) {
						Message msg_BH_SL = new Message();

						Vector<String> data_BH = new Vector<String>();
						if(GlobalConstant.isCheck_BH_BR)
							data_BH.add("Respiration Rate");
						if(GlobalConstant.isCheck_BH_HR)
							data_BH.add("Heart Rate");
						if(GlobalConstant.isCheck_BH_HRV)
							data_BH.add("HRV");

						String[] data = data_BH.toArray(new String[data_BH.size()]);
						msg_BH_SL.what = BH_SL;
						msg_BH_SL.obj = (Object) String.valueOf(scm.getStressLevel("BioHarness", data));
						dataHandler.sendMessage(msg_BH_SL); 
					}
				} catch (IllegalArgumentException e) {
					Log.d("Exception", e.getMessage());
				} catch (InterruptedException e) {
					Log.d("Exception", e.getMessage());
				}
			}
			Looper.loop();
			/* ------------------previous code ----------
			BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(bluetoothAddress); 
			mShimmerDevice1.connect(device); // Right Arm is a unique identifier for the shimmer unit
			Log.d("ChillConnection", "Trying");

			while(mShimmerDevice1.getState()==Shimmer.STATE_CONNECTING){}; // wait for the connecting state to finish
			if(mShimmerDevice1.getState()==Shimmer.STATE_CONNECTED){
				Log.d("ChillConnection", "Successful"); 
				Vibrator successV = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
				successV.vibrate(300);
				mShimmerDevice1.writeEnabledSensors(Shimmer.SENSOR_GSR); //enable GSR sensors ( should work with our installed Shimmer Firmware

				mShimmerDevice1.startStreaming();
			}
			else{
				Log.d("ChillConnection","Failed");
			}
			  ------------------previous code ----------
			 */
		}
		
		public void stopThread() {
			stillContinue = false;
			scm.disconnectSensors(sensor_names);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		super.onCreateOptionsMenu(menu);
		menu.add(0, MENU_COLORBLIND_MODE_ON, 0, 	R.string.menu_colorblind_mode_on);
		menu.add(0, MENU_COLORBLIND_MODE_OFF, 0, 	R.string.menu_colorblind_mode_off);
		menu.add(0, MENU_FULLSCREEN_ON, 0, 			R.string.menu_fullscreen_on);
		menu.add(0, MENU_FULLSCREEN_OFF, 0, 		R.string.menu_fullscreen_off);
		menu.add(0, MENU_SOUND_ON, 0, 				R.string.menu_sound_on);
		menu.add(0, MENU_SOUND_OFF, 0, 				R.string.menu_sound_off);
		menu.add(0, MENU_TOUCHSCREEN_AIM_THEN_SHOOT, 0,
				R.string.menu_touchscreen_aim_then_shoot);
		menu.add(0, MENU_TOUCHSCREEN_POINT_TO_SHOOT, 0,
				R.string.menu_touchscreen_point_to_shoot);
		menu.add(0, MENU_DONT_RUSH_ME, 0, 			R.string.menu_dont_rush_me);
		menu.add(0, MENU_RUSH_ME, 0, 				R.string.menu_rush_me);
		menu.add(0, MENU_ABOUT, 0, 					R.string.menu_about);
		menu.add(0, MENU_NEW_GAME, 0, 				R.string.menu_new_game);
		menu.add(0, MENU_EDITOR, 0, 				R.string.menu_editor);
		return true;
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu)
	{
		super.onPrepareOptionsMenu(menu);
		menu.findItem(MENU_SOUND_ON).setVisible(!getSoundOn());
		menu.findItem(MENU_SOUND_OFF).setVisible(getSoundOn());
		menu.findItem(MENU_COLORBLIND_MODE_ON).setVisible(
				getMode() == GAME_NORMAL);
		menu.findItem(MENU_COLORBLIND_MODE_OFF).setVisible(
				getMode() != GAME_NORMAL);
		menu.findItem(MENU_FULLSCREEN_ON).setVisible(!fullscreen);
		menu.findItem(MENU_FULLSCREEN_OFF).setVisible(fullscreen);
		menu.findItem(MENU_TOUCHSCREEN_AIM_THEN_SHOOT).setVisible(
				!getAimThenShoot());
		menu.findItem(MENU_TOUCHSCREEN_POINT_TO_SHOOT).setVisible(
				getAimThenShoot());
		menu.findItem(MENU_DONT_RUSH_ME).setVisible(!getDontRushMe());
		menu.findItem(MENU_RUSH_ME).setVisible(getDontRushMe());
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch (item.getItemId()) {
		case MENU_NEW_GAME:
			mGameThread.newGame();
			return true;
		case MENU_COLORBLIND_MODE_ON:
			setMode(GAME_COLORBLIND);
			return true;
		case MENU_COLORBLIND_MODE_OFF:
			setMode(GAME_NORMAL);
			return true;
		case MENU_FULLSCREEN_ON:
			fullscreen = true;
			setFullscreen();
			return true;
		case MENU_FULLSCREEN_OFF:
			fullscreen = false;
			setFullscreen();
			return true;
		case MENU_SOUND_ON:
			setSoundOn(true);
			return true;
		case MENU_SOUND_OFF:
			setSoundOn(false);
			return true;
		case MENU_ABOUT:
			mGameView.getThread().setState(GameView.GameThread.STATE_ABOUT);
			return true;
		case MENU_TOUCHSCREEN_AIM_THEN_SHOOT:
			setAimThenShoot(true);
			return true;
		case MENU_TOUCHSCREEN_POINT_TO_SHOOT:
			setAimThenShoot(false);
			return true;
		case MENU_DONT_RUSH_ME:
			setDontRushMe(true);
			return true;
		case MENU_RUSH_ME:
			setDontRushMe(false);
			return true;
		case MENU_EDITOR:
			startEditor();
			return true;
		}
		return false;
	}

	private void setFullscreen()
	{
		if (fullscreen) {
			getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
			getWindow().clearFlags(
					WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
		} else {
			getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
			getWindow().addFlags(
					WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
		}
		mGameView.requestLayout();
	}

	public synchronized static void setMode(int newMode)
	{
		gameMode = newMode;
	}

	public synchronized static int getMode()
	{
		return gameMode;
	}

	public synchronized static boolean getSoundOn()
	{
		return soundOn;
	}

	public synchronized static void setSoundOn(boolean so)
	{
		soundOn = so;
	}

	public synchronized static boolean getAimThenShoot()
	{
		return aimThenShoot;
	}

	public synchronized static void setAimThenShoot(boolean ats)
	{
		aimThenShoot = ats;
	}

	// Gmae control 
	public synchronized static boolean getDontRushMe()
	{
		return dontRushMe;
	}

	public synchronized static void setDontRushMe(boolean dont)
	{
		dontRushMe = dont;
	}

	//required variables for Shimmer syncronization, Shimmer may not work on Android 2.3.3 & above
	private Shimmer mShimmerDevice1 = null;
	private BluetoothAdapter mBluetoothAdapter = null;

	private String[] sensor_names;

	/** Called when the activity is first created. */
	@SuppressLint("NewApi")
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		/* -----------------------previous codes-----------------------
		//Shimmer Syncronization code
		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 

		while (!mBluetoothAdapter.isEnabled()) {
			Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
			startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
		}
		mShimmerDevice1 = new Shimmer(this, mHandler, "RightArm",false);

		thread = new BlueToothThread();
		thread.start();
		   -----------------------previous codes-----------------------
		 */

		if (savedInstanceState != null) {
			Log.i("frozen-bubble", "FrozenBubble.onCreate(...)");
		} else {
			Log.i("frozen-bubble", "FrozenBubble.onCreate(null)");
		}

		super.onCreate(savedInstanceState);
		ChillOut.fb = this;
		ChillOut.thread.setPlaying(true);
		ChillOut.thread.start();
		setVolumeControlStream(AudioManager.STREAM_MUSIC);
		requestWindowFeature(Window.FEATURE_NO_TITLE);

		// Allow editor functionalities.
		Intent i = getIntent();
		if (null == i || null == i.getExtras() ||
				!i.getExtras().containsKey("levels")) {
			// Default intent.
			activityCustomStarted = false;
			setContentView(R.layout.game_activity_main);
			mGameView = (GameView)findViewById(R.id.game);
		} else {
			// Get custom level last played.
			SharedPreferences sp = getSharedPreferences(
					FrozenBubble.PREFS_NAME, Context.MODE_PRIVATE);
			int startingLevel = sp.getInt("levelCustom", 0);
			int startingLevelIntent = i.getIntExtra("startingLevel", -2);
			startingLevel = (startingLevelIntent == -2) ?
					startingLevel : startingLevelIntent;
			activityCustomStarted = true;
			mGameView = new GameView(this, i.getExtras().getByteArray("levels"), startingLevel);
			setContentView(mGameView);
		}

		mGameThread = mGameView.getThread();

		if (savedInstanceState != null) {
			mGameThread.restoreState(savedInstanceState);
		}
		mGameView.requestFocus();
		setFullscreen();

		Log.d("Test", "In Activity FrozenBubble.java");



		thread = new BlueToothThread();
		thread.start();
	}

	public void appendLog(String text)
	{       
		File logFile = new File("sdcard/log.txt");
		if (!logFile.exists())
		{
			try
			{
				logFile.createNewFile();
			} 
			catch (IOException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		try
		{
			//BufferedWriter for performance, true to set append to file flag
			BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true)); 
			buf.append(text);
			buf.newLine();
			buf.close();
		}
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}  

	//Handler for Shimmer Data, currently set for Accelerometer for Testing Purposes
//	private final Handler mHandler = new Handler()
//	{ 
//		public void handleMessage(Message msg)
//		{ 
			//			switch (msg.what)
			//			{ 
			//			case Shimmer.MESSAGE_READ: 
			//				if ((msg.obj instanceof ObjectCluster))
			//				{ 
			//					ObjectCluster objectCluster = (ObjectCluster) msg.obj; 
			//					if (objectCluster.mMyName=="RightArm")
			//					{ 
			//						Collection<FormatCluster> GSRFormats = objectCluster.mPropertyCluster.get("GSR"); //This line is probably not correct, I need to read into it.
			//						if (GSRFormats != null)
			//						{ 
			//							FormatCluster formatCluster = 
			//									((FormatCluster)objectCluster.returnFormatCluster(GSRFormats,"Calibrated"));
			//
			//							long t = System.currentTimeMillis() - timestamp;
			//							//Log.d("ChillData", "GSR: " + t + " " + SC + " uS"); 
			//							//unit: formatCluster.mUnits
			//							Log.d("ChillData", "GSR: " + t + " ms " + (1000/formatCluster.mData) + " uS"); 
			//							currentGSRvector.add(formatCluster.mData);
			//
			//							// log.txt gives all ten values it reads, every second
			//							appendLog( t + " ms " + formatCluster.mData + " uS");
			//
			//							if(currentGSRvector.size() >= 10)
			//							{
			//								currentGSR = 0;
			//								for(int i = 0 ; i < 10 ; i++)
			//								{
			//									currentGSR = currentGSR + (currentGSRvector.elementAt(i));
			//								}
			//								currentGSR = (currentGSR/10.0);
			//								currentGSR = (1000.0/currentGSR);
			//								GSR = currentGSR;
			//								currentGSRvector.remove(0);
			//							}
			//						}
			//						else
			//							Log.d("ChillData", "GSR is null"); 
			//
			//					} 
			//				} 
			//				break; 
			//			case Shimmer.MESSAGE_TOAST: 
			//				//Log.d("ChillToast",msg.getData().getString(Shimmer.TOAST)); 
			//				// Toast.makeText(getApplicationContext(), msg.getData().getString(Shimmer.TOAST), 
			//				// Toast.LENGTH_SHORT).show(); 
			//				break; 
			//			} 
//		} 
//	};


	public double returnGSR(){
		return (GSR);
	};	  


	/**
	 * Invoked when the Activity loses user focus.
	 */
	@Override
	protected void onPause() {
		//Log.i("frozen-bubble", "FrozenBubble.onPause()");
		super.onPause();
		mGameView.getThread().pause();
		ChillOut.thread.setPlaying(false);
		// Allow editor functionalities.
		Intent i = getIntent();
		// If I didn't run game from editor, save last played level.
		if (null == i || !activityCustomStarted) {
			SharedPreferences sp = getSharedPreferences(PREFS_NAME,
					Context.MODE_PRIVATE);
			SharedPreferences.Editor editor = sp.edit();
			editor.putInt("level", mGameThread.getCurrentLevelIndex());
			editor.commit();
		} else {
			// Editor's intent is running.
			SharedPreferences sp = getSharedPreferences(PREFS_NAME,
					Context.MODE_PRIVATE);
			SharedPreferences.Editor editor = sp.edit();
			editor.putInt("levelCustom", mGameThread.getCurrentLevelIndex());
			editor.commit();
		}
	}

	@Override
	protected void onStop() {
		super.onStop();
		Log.d("Finished", "HelloStop");
//		boolean isStop = mShimmerDevice1.
//		mShimmerDevice1.stopStreaming();	//assuming onStop is called when the game is finished, this makes the shimmer stop as well.
//		mShimmerDevice1.stop();
//
//		ChillOut.thread.setPlaying(false);

		//Log.i("frozen-bubble", "FrozenBubble.onStop()");
	}

	@Override
	protected void onDestroy() {
		//Log.i("frozen-bubble", "FrozenBubble.onDestroy()");
		super.onDestroy();
//		mShimmerDevice1.stopStreaming();
//		mShimmerDevice1.stop();
//		if (mGameView != null) {
//			mGameView.cleanUp();
//		}
//		mGameView = null;
//		mGameThread = null; 
		thread.stopThread();

		ChillOut.thread.setPlaying(false);
	}

	/**
	 * Notification that something is about to happen, to give the Activity a
	 * chance to save state.
	 *
	 * @param outState a Bundle into which this Activity should save its state
	 */
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		//Log.i("frozen-bubble", "FrozenBubble.onSaveInstanceState()");
		// Just have the View's thread save its state into our Bundle.
		super.onSaveInstanceState(outState);
		mGameThread.saveState(outState);
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onNewIntent(android.content.Intent)
	 */
	@Override
	protected void onNewIntent(Intent intent) {
		if (null != intent && EDITORACTION.equals(intent.getAction())) {
			if (!activityCustomStarted) {
				activityCustomStarted = true;

				// Get custom level last played.
				SharedPreferences sp = getSharedPreferences(
						FrozenBubble.PREFS_NAME, Context.MODE_PRIVATE);
				int startingLevel = sp.getInt("levelCustom", 0);
				int startingLevelIntent = intent.getIntExtra("startingLevel", -2);
				startingLevel = (startingLevelIntent == -2) ?
						startingLevel : startingLevelIntent;

				mGameView = null;
				mGameView = new GameView(
						this, intent.getExtras().getByteArray("levels"),
						startingLevel);
				setContentView(mGameView);
				mGameThread = mGameView.getThread();
				mGameThread.newGame();
				mGameView.requestFocus();
				setFullscreen();
			}
		}
	}

	// Starts editor / market with editor's download.
	private void startEditor()
	{
		Intent i = new Intent();
		// First try to run the plus version of Editor.
		i.setClassName("sk.halmi.fbeditplus", 
				"sk.halmi.fbeditplus.EditorActivity");
		try {
			startActivity(i);
			finish();
		} catch (ActivityNotFoundException e) {
			// If not found, try to run the normal version.
			i.setClassName("sk.halmi.fbedit", 
					"sk.halmi.fbedit.EditorActivity");
			try {
				startActivity(i);
				finish();
			} catch (ActivityNotFoundException ex) {
				// If user doesnt have Frozen Bubble Editor take him to market.
				try {
					Toast.makeText(getApplicationContext(), 
							R.string.install_editor, Toast.LENGTH_SHORT).show();
					startActivity(i);
				} catch (Exception exc) {
					// Damn you don't have market?
					Toast.makeText(getApplicationContext(), 
							R.string.market_missing, Toast.LENGTH_SHORT).show();
				}
			}
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		if ((keyCode == KeyEvent.KEYCODE_BACK))
		{
			finish();

			//Attempting to go back to the Title Screen
			Intent title_intent = new Intent(FrozenBubble.this, ChillOut.class);
			startActivity(title_intent);

		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onBackPressed() {
	}
}
